/*
 * Data Explorer: Utility (Helper) Functions for Main Control File
 *      control.js
 *
 * last modified: 12/27/10
 * author: James Duran
 *
 * description: Provides various utility functions that the main control
 *              file can use. This include functions for displaying map
 *              markers, performing box window searches, and geocode
 *              conversions.
 *
 * comments: n/a
 */

// application constants (even though there are no constants in javascript)
var SEARCH_TAGS = "php/tags.php";
var PROXIMITY_SEARCH = "php/proximitySearch.php";
var SEARCH_QUERY = "php/query.php";
var ADDITIONAL_SOURCES = "php/additionalSources.php";
var FOOTNOTES = "php/footnoteDriver.php";

// getURLVars:
//
// a jquery extension to get all URL parameters from the URL
// -------------------------------------------------------------------
// getURLVar:
//
// a jquery extension that returns the value of a specific parameter
$.extend({getURLVars: function() {
	    var vars = [], hash;
	    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	    for(var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	    }
	    return vars;
	},
	  getURLVar: function(name) {
	    return $.getURLVars()[name];
	}
    });

// arrayToString:
//
// joins an array into a single string to be returned,
// separated by an indicated delimiter.
function arrayToString(delimiter, inArray, isReverse) {
    var _tmp = "";
    if(isReverse == false) {
	for(var _i in inArray) {
	    if(_i == 0)
		_tmp = inArray[_i];
	    else
		_tmp += delimiter + inArray[_i];
        }
    } else { // if isReverse is true construct the string in reverse
	for(var _i = inArray.length - 1; _i >= 0; _i--) {
	    if(_i == inArray.length - 1)
		_tmp = inArray[_i];
	    else
		_tmp += delimiter + inArray[_i];
	}
    }
    return _tmp;
}

// autoCenterNodes:
//
// retrieves all nodes within nodeArray and calculates the best position to center
// on the google map element, such that all map nodes will be visible to the user.
function autoCenterNodes() {
    //  Create a new viewpoint bound
    var bounds = new google.maps.LatLngBounds();
    //  Go through each...
    $.each(nodeArray, function (index, marker) {
            bounds.extend(marker.position);
        });
    //  Fit these bounds to the map
    map.fitBounds(bounds);
}

// convertTo12Hour:
//
// given a 24 hour format, 00 - 23, convert the time to
// fit a 12 hour am/pm range.
function convertTo12Hour(hour) {
    var _tmp = parseInt(hour, 10);
    var _out = "";
    if(_tmp <= 11 && _tmp != 0)
	_out = _tmp + " am";
    else if(_tmp == 12)
	_out = _tmp + " pm";
    else if(_tmp > 12 && _tmp < 24)
	_out = (_tmp - 12) + " pm";
    else if(_tmp == 0)
	_out = (_tmp + 12) + " am";
    else
	_out = "0";
    return _out;
}

// geocodeGetAddress:
//
// uses Google's javascript geocoding api to reverse lookup addresses based
// on a given latitude/longitude. Limited to ~2,300 queries a day.
function geocodeGetAddress(latitude, longitude) {
    formattedAddress = "The geocoder cannot provide an address at this time.";
    // global geocoder object
    var geocoder = new google.maps.Geocoder();
    var _latlng = new google.maps.LatLng(parseFloat(latitude), parseFloat(longitude));
    geocoder.geocode({'latLng': _latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            // results[0] contains the most specific address (if found)
            if (results[0]) {
                formattedAddress = results[0].formatted_address + "";
            }
        } else {
            formattedAddress = "The geocoder could not find the address. (" + status + ")";
        }
    });
}

// getRootURL:
//
// retrieve the root document URL represented in the web browser,
// free of any parameter variables.
function getRootURL() {
    // the root URL, without any parameters, will be the first array element
    var _urlString = window.location.href;
    var _urlArray = _urlString.split("?");
    return _urlArray[0];
}

// JSONQuery:
//
// constructs a general json query using the jsonp format. Note
// that this function uses .jsonp, which is an external utility
// outside the JQuery library. This is mainly because JQuery does not
// handle timeout error messages correctly in its own jsonp utility.
function JSONQuery(urlRequest, successCallback, attributes) {
        // create a json request to retrieve faa web service data
        $.jsonp({url: urlRequest + attributes,
	    dataFilter: successCallback,
	    timeout: 10000,
	    //success: successCallback,
            error: function(xOptions, textStatus) {
		    if(textStatus == "timeout") {
			showTimeoutErrorDialog();
		    } else {
                        showGeneralErrorDialog();
		    }
		   }});
}

// selectAllText
//
// utility event function to select all text within a textbox
function selectAllText(element) {
    element.focus();
    element.select();
}

// unsetMapNodes:
//
// resets the marker node array, setting all marker elements
// to null, and finally setting the array back to length 0.
function unsetMapNodes(array) {
    for(_x in array) {
	// set the map marker to null
	array[_x].setMap(null);
    }
    // reset the array length
    array.length = 0;
}

// XMLQuery:
//
// describes a general xml query, based on a given url and a
// success callback function. Includes a timout of 10 seconds and
// a timeout/general error dialog.
function XMLQuery(urlAddress, successCallback) {
    $.ajax({type: "GET",
	    url: urlAddress,
	    dataType: "xml",
	    success: successCallback,
            timeout: 10000,
	    error: function(XMLHttpRequest, textStatus, errorThrown) {
		if(textStatus == "timeout") {
		    showTimeoutErrorDialog();
		} else {
		    showGeneralErrorDialog();
		}
	    }});
}
